<template>
  <basic-container>

    <el-collapse>
      <el-collapse-item name="1">
        <template #title>
          <el-text type="info">
            <el-icon>
              <Warning />
            </el-icon>
            提示：
          </el-text>
        </template>
        <div>
          <el-text type="info">
            1.导出时，先 ”搜索“，再 ”导出“。否则查询条件不会生效。
          </el-text>
        </div>
        <div>
          <el-text type="info">
            2.”实到数量” 和 ”金额“ 排序，只针对当前页数据有效。（可以对当前页查询条数增加）
          </el-text>
        </div>
      </el-collapse-item>
    </el-collapse>

    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               @row-dblclick="handleRowDBLClick"
               @sort-change="sortChange"
    >
      <template #menu-left>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.commoditysummary_edit"
                   @click="handleExport">导出
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   icon="el-icon-document-add"
                   v-if="permission.commoditysummary_edit"
                   @click="handleReplacement">补单
        </el-button>
      </template>

      <template #menu="{row}">
        <el-button text
                   type="primary"
                   icon="el-icon-setting"
                   v-if="permission.commoditysummary_edit"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click.stop="handleDistribute(row)">分配
        </el-button>
      </template>

      <template #status="{row}">
        <el-tag v-if="row.status === 1" type="warning">{{ row.$status }}</el-tag>
        <el-tag v-else-if="row.status === 3" type="danger">{{ row.$status }}</el-tag>
        <el-tag v-else type="success">{{ row.$status }}</el-tag>
      </template>

      <template #difference="{row}">
        <el-text v-if="row.difference > 0" type="success">{{ row.difference }}</el-text>
        <el-text v-else-if="row.difference < 0" type="danger">{{ row.difference }}</el-text>
        <el-text v-else type="info">{{ row.difference }}</el-text>
      </template>
      <template #enterStatus="{row}">
        <el-tag v-if="row.enterStatus === 2" type="success">{{ row.$enterStatus }}</el-tag>
        <el-tag v-else-if="row.enterStatus === 1" type="warning">{{ row.$enterStatus }}</el-tag>
        <el-tag v-else type="info">未分配</el-tag>
      </template>
    </avue-crud>

    <el-drawer :title="`【${categoryName}-${commodityName}】 分配`"
               v-model="drawerVisible"
               :direction="direction"
               append-to-body
               :before-close="handleDrawerClose"
               size="70%">
      <basic-container>
        <avue-crud
          :option="infoOption"
          :data="dataInfo"
          :page="pageInfo"
          v-model="formInfo"
          :table-loading="infoLoading"
          ref="crudInfo"
          @row-update="infoRowUpdate"
          @on-load="onLoadInfo"
        ></avue-crud>
      </basic-container>
    </el-drawer>

    <el-drawer :title="`补单`"
               v-model="drawerVisibleReplacement"
               :direction="direction"
               append-to-body
               size="50%">
      <basic-container>
        <avue-form :option="optionReplacement" v-model="formReplacement"  @submit="handleReplacementSubmit"></avue-form>
      </basic-container>
    </el-drawer>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/restaurant/commoditysummary';
import { mapGetters } from 'vuex';
import {
  update as infoRowUpdate,
  getPage as getListDataInfo
} from '@/api/restaurant/commodityrecordrelation';
import { getToken } from '@/utils/auth';
import { serialize } from '@/utils/util';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        cellBtn: true,  // 是否显示行内按钮
        showSummary: true,
        sumColumnList: [
          { name: 'number', type: 'sum' },
          { name: 'actualNumber', type: 'sum' },
          { name: 'amount', type: 'sum', decimals: 2 }
        ],
        column: [
          {
            label: '到货日期',
            hide: true,
            prop: 'searchTime',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            search: true,
            searchSpan: 8,
            searchRange: true,
            disabledDate(time) {
              return time.getTime() > Date.now();
            }
          },
          {
            label: '采购日期',
            hide: true,
            prop: 'purchaseTime',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{
              required: true,
              message: '请输入采购日期',
              trigger: 'blur'
            }]
          },

          {
            label: '到货日期',
            prop: 'arrivalDate',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{
              required: true,
              message: '请输入到货日期',
              trigger: 'blur'
            }]
          },
          {
            label: '采购类别',
            prop: 'categoryId',
            type: 'select',
            search: true,
            props: {
              label: 'categoryName',
              value: 'id'
            },
            dicUrl: '/api/restaurant/purchasecategory/dic',
            rules: [{
              required: true,
              message: '请输入采购类别ID',
              trigger: 'blur'
            }]
          },
          {
            label: '排序',
            prop: 'sort',
            hide: true,
            rules: [{
              required: true,
              message: '请输入排序',
              trigger: 'blur'
            }]
          },
          {
            label: '货物名',
            prop: 'commodityName',
            search: true,
            rules: [{
              required: true,
              message: '请输入货物名',
              trigger: 'blur'
            }]
          },
          {
            label: '商品图',
            prop: 'productPicture',
            type: 'upload',
            listType: 'picture-card',
            action: '/api/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            span: 24,
            minRows: 4,
            rules: [{
              required: true,
              message: '请输入商品图',
              trigger: 'blur'
            }]
          },
          {
            label: '单位',
            prop: 'unit',
            rules: [{
              required: true,
              message: '请输入单位',
              trigger: 'blur'
            }]
          }, {
            label: '状态',
            prop: 'status',
            type: 'select',
            cell: true,
            rules: [{
              required: true,
              message: '请输入状态',
              trigger: 'blur'
            }],
            dicData: [{
              label: '未到货',
              value: 1
            }, {
              label: '已到货',
              value: 2
            }, {
              label: '撤单',
              value: 3
            }],
            search: true
          },
          {
            label: '申购数量',
            prop: 'number',
            type: 'number',
            precision: 0,
            min: 0,
            rules: [{
              required: true,
              message: '请输入数量',
              trigger: 'blur'
            }]
          },
          {
            sortable: true, // 排序
            label: '实到数量',
            prop: 'actualNumber',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入实到数量',
              trigger: 'blur'
            }],
            focus: ({ value, column }) => {
            },
            blur: ({ value, column }) => {
            },
            enter: ({ value, column }) => {
            }
          },
          {
            label: '数量差额',
            prop: 'difference',
            type: 'number',
            precision: 2,
            min: 0,
            rules: [{
              required: true,
              message: '请输入数量差额',
              trigger: 'blur'
            }]
          },
          {
            sortable: true, // 排序
            label: '金额',
            prop: 'amount',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入金额',
              trigger: 'blur'
            }]
          },
          {
            label: '单价',
            prop: 'unitPrice',
            rules: [{
              required: true,
              message: '请输入单价',
              trigger: 'blur'
            }]
          },
          {
            label: '分配状态',
            prop: 'enterStatus',
            type: 'select',
            cell: true,
            rules: [{
              required: true,
              message: '请输入分配状态',
              trigger: 'blur'
            }],
            dicData: [{
              label: '未分配',
              value: 0
            }, {
              label: '部分分配',
              value: 1
            }, {
              label: '全部分配',
              value: 2
            }],
            search: true
          }, {
            label: '备注',
            prop: 'remark',
            cell: true,
            rules: [{
              message: '请输入备注',
              trigger: 'blur'
            }]
          }

        ]
      },
      data: [],

      // 分配
      drawerVisible: false,
      direction: 'rtl',
      commodityId: '',
      categoryName: '',
      commodityName: '',
      purchaseTime: '',
      infoLoading: false,
      formInfo: {},
      selectionListScope: [],
      pageInfo: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      dataInfo: [],
      infoOption: {
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        cellBtn: true,  // 是否显示行内按钮
        selection: false,
        showSummary: true, // 统计
        sumColumnList: [
          { name: 'number', type: 'sum', decimals: 1 },
          { name: 'actualNumber', type: 'sum', decimals: 1 }
        ],
        column: [
          {
            label: '下单人',
            prop: 'userName',
            rules: [{
              required: true,
              message: '请输入下单人',
              trigger: 'blur'
            }]
          },
          {
            label: '货物名',
            prop: 'commodityName',
            rules: [{
              required: true,
              message: '请输入货物名',
              trigger: 'blur'
            }]
          },
          {
            label: '类别名',
            prop: 'categoryName',
            rules: [{
              required: true,
              message: '请输入类别名',
              trigger: 'blur'
            }]
          },
          {
            label: '货物图',
            prop: 'productPicture',
            type: 'upload',
            listType: 'picture-img',
            action: '/api/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            rules: [{
              required: true,
              message: '请输入货物图',
              trigger: 'blur'
            }]
          },
          {
            label: '单位',
            prop: 'unit',
            rules: [{
              required: true,
              message: '请输入单位',
              trigger: 'blur'
            }]
          },
          {
            label: '申购数量',
            prop: 'number',
            type: 'number',
            precision: 0,
            min: 0,
            rules: [{
              required: true,
              message: '请输入数量',
              trigger: 'blur'
            }]
          },
          {
            label: '实到数量',
            prop: 'actualNumber',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入实到数量',
              trigger: 'blur'
            }]
          }, {
            label: '数量差额',
            prop: 'difference',
            type: 'number',
            precision: 2,
            min: 0,
            rules: [{
              required: true,
              message: '请输入数量差额',
              trigger: 'blur'
            }]
          },
          {
            sortable: true, // 排序
            label: '金额',
            prop: 'amount',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入金额',
              trigger: 'blur'
            }]
          },
          {
            label: '单价',
            prop: 'unitPrice',
            rules: [{
              required: true,
              message: '请输入单价',
              trigger: 'blur'
            }]
          }

        ]
      },

      // 补单
      drawerVisibleReplacement: false,
      optionReplacement: {
        column: [
          {
            label: '采购日期',
            prop: 'purchaseTime',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{
              required: true,
              message: '请输入采购日期',
              trigger: 'blur'
            }]
          },
          {
            label: '到货日期',
            prop: 'arrivalDate',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{
              required: true,
              message: '请输入到货日期',
              trigger: 'blur'
            }]
          },
          {
            label: '采购类别',
            prop: 'categoryId',
            type: 'select',
            search: true,
            props: {
              label: 'categoryName',
              value: 'id'
            },
            dicUrl: '/api/restaurant/purchasecategory/dic',
            cascader: ['commodityId'],
            rules: [{
              required: true,
              message: '请输入采购类别ID',
              trigger: 'blur'
            }]
          },

          {
            label: '货物名',
            prop: 'commodityId',
            type: 'select',
            dicUrl: `/api/restaurant/purchasecommodity/listByCategory/{{key}}`,
            props: {
              label: 'commodityName',
              value: 'id'
            },
            rules: [{
              required: true,
              message: '请输入货物名',
              trigger: 'blur'
            }]
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            rules: [{
              required: true,
              message: '请输入状态',
              trigger: 'blur'
            }],
            dicData: [{
              label: '未到货',
              value: '1'
            }, {
              label: '已到货',
              value: '2'
            }],
            search: true
          },
          {
            label: '申购数量',
            prop: 'number',
            type: 'number',
            precision: 0,
            min: 0,
            rules: [{
              required: true,
              message: '请输入数量',
              trigger: 'blur'
            }]
          },
          {
            sortable: true, // 排序
            label: '实到数量',
            prop: 'actualNumber',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入实到数量',
              trigger: 'blur'
            }]
          },
          {
            sortable: true, // 排序
            label: '金额',
            prop: 'amount',
            type: 'number',
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: '请输入金额',
              trigger: 'blur'
            }]
          },
          {
            label: '备注',
            prop: 'remark',
            cell: true,
            rules: [{
              message: '请输入备注',
              trigger: 'blur'
            }]
          }

        ]
      },
      formReplacement: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: this.validData(this.permission.commoditysummary_view, false),
        delBtn: false,
        editBtn: this.validData(this.permission.commoditysummary_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleRowDBLClick(row, column, cell, event) {
      // 双击行编辑
      this.$refs.crud.rowCellEdit(row);
    },
    sortChange(column) {
      // 排序 是否请求后台接口 暂时不请求
    },

    // 补单
    handleReplacement() {
      this.drawerVisibleReplacement = true;
    },
    handleReplacementSubmit(row, done){
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.drawerVisibleReplacement = false;
      }, error => {
        window.console.log(error);
      });
    },


    // 分配
    handleDistribute(row) {
      this.drawerVisible = true;
      this.purchaseTime = row.purchaseTime;
      this.commodityId = row.commodityId;
      this.commodityName = row.commodityName;
      this.categoryName = row.categoryName;
      this.onLoadInfo(this.pageInfo);
    },
    handleDrawerClose(hide) {
      hide();
    },
    infoRowUpdate(row, index, done, loading) {
      infoRowUpdate(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    onLoadInfo(page, params = {}) {
      this.infoLoading = true;
      const values = {
        ...params,
        purchaseTime: this.purchaseTime,
        commodityId: this.commodityId
      };
      getListDataInfo(page.currentPage, page.pageSize, Object.assign(values, this.query)).then(res => {
        const data = res.data.data;
        this.pageInfo.total = data.total;
        this.dataInfo = data.records;
        this.infoLoading = false;
      });
    },

    async handleExport() {
      this.$confirm(`确定导出采购汇总数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('导出查询条件：', serialize(this.query));
        window.open(`/api/restaurant/commoditysummary/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
      });
    },

    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
